﻿/** 
 * Copyright 2010 NUMKIT.COM (contact: opensource@numkit.com)
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 * 
 * @author 陈超
 * @version 1.0
 */
import flash.external.ExternalInterface;
import flash.display.BitmapData;
import flash.geom.Matrix;
class IconSet {
	private var aIconBmp:Array;
	private var imageLoader:MovieClipLoader;
	private var onAllIconsLoaded:Function;
	private var intervalID:Number;
	public function IconSet(node:XMLNode, tempMC:MovieClip, onAllLoaded:Function) {
		if (node.nodeName != "icons") {
			throw new Error("Not a icons node!");
		}
		this.onAllIconsLoaded = onAllLoaded;
		aIconBmp = new Array();
		imageLoader = new MovieClipLoader();
		imageLoader.addListener(this);
		for (var child:XMLNode = node.firstChild; child != null; child=child.nextSibling) {
			var nodeName:String = child.nodeName;
			if (nodeName == "icon") {
				var type:String = child.attributes["type"];
				var url:String = child.firstChild.nodeValue;
				var mc:MovieClip = tempMC.createEmptyMovieClip(type, tempMC.getNextHighestDepth());
				aIconBmp[type] = "loading";
				imageLoader.loadClip(url, mc);
			}
		}
		intervalID = setInterval(this, "testLoad", 100);
	}
	public function onLoadInit(imageClip:MovieClip):Void {
		var bmp:BitmapData = new BitmapData(imageClip._width, imageClip._height);
		bmp.draw(imageClip, new Matrix());
		aIconBmp[imageClip._name] = bmp;
	}
	public function onLoadError(imageClip:MovieClip, errorCode:String, httpStatus:Number) {
		aIconBmp[imageClip._name] = null;
	}
	public function getIconArray():Array {
		return aIconBmp;
	}
	public function testLoad():Void {
		var loading:Boolean = false;
		for (var type in aIconBmp) {
			if (aIconBmp[type] == "loading") {
				loading = true;
			}
		}
		if (!loading) {
			onAllIconsLoaded();
			clearInterval(intervalID);
		}
	}
}
